package com.etung.iot.demo.handler;

import com.alibaba.fastjson.JSONObject;
import com.etung.iot.demo.configs.TopicConfig;
import com.etung.iot.demo.constant.CommonConstant;
import com.etung.iot.demo.dao.RealDataMapper;
import com.etung.iot.demo.dao.UserMapper;
import com.etung.iot.demo.modles.RealData;
import com.etung.iot.demo.runner.StorageRunner;
import com.etung.iot.demo.storage.conTriggerStorage.PreConditionStorageUtil;
import com.etung.iot.demo.utils.RedisUtil;
import com.etung.iot.demo.websocket.MyWebSocket;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Handler(TopicConfig.REAL_DATA_TOPIC)
@Slf4j
public class RealDataHandler implements TopicHandler{

    @Autowired
    private RealDataMapper realDataMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MyWebSocket myWebSocket;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserCacheUtil userCacheUtil;
    @Autowired
    private PreConditionStorageUtil preConditionStorageUtil;

    @Override
    public void handler(String topic,String payload) {
        log.info("payload:"+payload);
        JSONObject jsonObject = JSONObject.parseObject(payload);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<RealData> realDataList = Lists.newArrayList();
        String imei = "";
        Date time = null;
        if(jsonObject.containsKey("imei") && jsonObject.containsKey("time")){
            imei = jsonObject.getString("imei");
            time = new Date(jsonObject.getLong("time"));
        }
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            if(StringUtils.isNumeric(entry.getKey())){
                RealData realData = new RealData();
                realData.setImei(imei);
                realData.setVarId(Integer.parseInt(entry.getKey()));
                realData.setValue(String.valueOf(entry.getValue()));
                realData.setTime(time);
                realDataList.add(realData);
                String cacheKey =CommonConstant.REAL_DATA_CACHE_PREFIX + imei +"_" + realData.getVarId();
                if(!StringUtils.isEmpty(realData.getValue())){
                    redisUtil.setWithExpire(cacheKey,realData);
                    if (preConditionStorageUtil.isIncludeChangeConStorage(imei,realData.getVarId())){
                        //当前变量是变化存储中监控变量
                        preConditionStorageUtil.saveChangeTypeLastRealData(imei,realData);
                    }
                }else{
                   if (redisUtil.hasKey(cacheKey)){
                       redisUtil.del(cacheKey);
                   }
                }
            }
        }
        if(realDataList.size() > 0){
            realDataList.forEach(realData -> {
                if(!StringUtils.isEmpty(realData.getValue())){
                    try {
                        StorageRunner.queue.put(realData);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            jsonObject.put("msg_type",TopicConfig.MESSAGE_TYPE_REAL_DATA);
//            myWebSocket.pushRealData(WebSocketConstant.BROADCAST,jsonObject.toJSONString());
            //查找当前box所属用户
            String uid = userCacheUtil.getUid(imei);
            if(!StringUtils.isEmpty(uid)){
                myWebSocket.pushRealData(uid,jsonObject.toJSONString());
            }
//            realDataMapper.insertList(realDataList);
        }


    }
}
